﻿using System;
using System.Collections.Generic;

namespace TicTacToe.Core.AI
{
    sealed class AIGameField
    {
        readonly int[][][] mArray;

        public int this[int x, int y, int z]
        {
            get
            {
                if (x < 0 || x > 3 || y < 0 || y > 3 || z < 0 || z > 3)
                    return int.MinValue;
                return mArray[x][y][z];
            }
            private set
            {
                mArray[x][y][z] = value;
            }
        }

        public static AIGameField FromGame(TicTacToeGame game)
        {
            var instance = new AIGameField();
            foreach (var turn in game.Turns)
                instance[turn.X1, turn.X2, turn.X3] = (turn.Player == game.PlayerOne) ? 1 : 2;
            return instance;
        }

        public bool IsFree(int x, int y, int z)
        {
            return this[x, y, z] == 0;
        }

        public IEnumerable<Tuple<int, int, int>> GetFreeFields()
        {
            var fields = new List<Tuple<int, int, int>>();
            for (int x = 0; x < 4; x++)
                for (int y = 0; y < 4; y++)
                    for (int z = 0; z < 4; z++)
                        if (this[x, y, z] == 0)
                            fields.Add(new Tuple<int, int, int>(x, y, z));
            return fields;
        }

        public AIGameField()
        {
            mArray = new int[][][]
            {
                new int[][]
                {
                    new int[4],
                    new int[4],
                    new int[4],
                    new int[4]
                },
                new int[][]
                {
                    new int[4],
                    new int[4],
                    new int[4],
                    new int[4]
                },
                new int[][]
                {
                    new int[4],
                    new int[4],
                    new int[4],
                    new int[4]
                },
                new int[][]
                {
                    new int[4],
                    new int[4],
                    new int[4],
                    new int[4]
                }
            };
        }
    }
}
